import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 侧边栏状态
  const sidebar = ref({
    opened: localStorage.getItem('sidebarStatus') ? !!+localStorage.getItem('sidebarStatus') : true,
    withoutAnimation: false
  })

  // 设备类型
  const device = ref('desktop')

  // 主题
  const theme = ref(localStorage.getItem('theme') || 'light')

  // 组件大小
  const size = ref(localStorage.getItem('size') || 'default')

  // 是否显示设置面板
  const showSettings = ref(false)

  // 计算属性
  const sidebarOpened = computed(() => sidebar.value.opened)
  const isMobile = computed(() => device.value === 'mobile')
  const currentTheme = computed(() => theme.value)
  const currentSize = computed(() => size.value)

  // 切换侧边栏
  const toggleSidebar = (withoutAnimation) => {
    sidebar.value.opened = !sidebar.value.opened
    sidebar.value.withoutAnimation = withoutAnimation
    if (sidebar.value.opened) {
      localStorage.setItem('sidebarStatus', 1)
    } else {
      localStorage.setItem('sidebarStatus', 0)
    }
  }

  // 关闭侧边栏
  const closeSidebar = (withoutAnimation) => {
    sidebar.value.opened = false
    sidebar.value.withoutAnimation = withoutAnimation
    localStorage.setItem('sidebarStatus', 0)
  }

  // 切换设备
  const toggleDevice = (deviceType) => {
    device.value = deviceType
  }

  // 切换主题
  const toggleTheme = (themeType) => {
    theme.value = themeType
    localStorage.setItem('theme', themeType)
    // 应用主题到html元素
    if (themeType === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 切换组件大小
  const setSize = (sizeType) => {
    size.value = sizeType
    localStorage.setItem('size', sizeType)
  }

  // 切换设置面板
  const toggleSettings = () => {
    showSettings.value = !showSettings.value
  }

  // 初始化主题
  const initTheme = () => {
    if (theme.value === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  return {
    sidebar,
    device,
    theme,
    size,
    showSettings,
    sidebarOpened,
    isMobile,
    currentTheme,
    currentSize,
    toggleSidebar,
    closeSidebar,
    toggleDevice,
    toggleTheme,
    setSize,
    toggleSettings,
    initTheme
  }
})